import emitter from 'event-emitter'
export default class WebScoketManager {
  constructor() {
    // 连接状态
    this.connState = false
    this.emitter = emitter()
    this.initWebSocket()
  }
  initWebSocket() {
    const address = process.env.VUE_APP_WEBSOCKET_API
    if (!address) { return }
    const ws = new window.WebSocket(address + '?cid=singleton') // process.env.VUE_APP_WEBSOCKET_API
    const me = this

    ws.onopen = function(e) {
      this.connState = true
      me.onOpen(e)
    }
    ws.onclose = function() {
      me.ws = null
      me.reConnection()
      me.onClose()
    }
    ws.onmessage = function(e) {
      me.onMessage(e)
    }

    this.ws = ws
  }
  reConnection() {
    if (!this.connState) {
      setTimeout(() => {
        console.log('重新连接websocket')
        this.initWebSocket()
      }, 5000)
    }
  }
  onOpen(e) {
    console.log('websocket已连接')  //'Openened connection to websocket'
  }
  onClose() {
    console.log('websocket已关闭') //'Close connection to websocket'
  }
  onMessage(e) {
    // console.log(e)
    const msg = JSON.parse(e.data)
    this.emitter.emit('onmessage', msg, e)
  }
  on(eventName, callback) {
    this.emitter.on(eventName, callback)
  }
  off(eventName, callback) {
    this.emitter.off(eventName, callback)
  }
}
